<template>
  <div class="browsing-history-page">
    <!-- 头部导航栏 -->
    <van-nav-bar
      title="浏览历史"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      class="header-bar"
    >
      <template #right>
        <van-icon name="delete-o" @click="clearHistory" class="text-lg" />
      </template>
    </van-nav-bar>

    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 统计信息 -->
      <div class="stats-section" v-if="roomList?.length">
        <div class="stats-card">
          <van-icon name="eye-o" class="stats-icon" />
          <div class="stats-info">
            <div class="stats-number">{{ roomList.length }}</div>
            <div class="stats-label">浏览记录</div>
          </div>
        </div>
      </div>

      <!-- 房间列表 -->
      <div class="content-container">
        <PullDownRefreshContainer
          :request="getHistoryListHandler"
          ref="pullDownRefreshContainerRef"
          class="min-h-[60vh]"
        >
          <template v-if="roomList?.length">
            <div class="room-list">
              <RoomCard v-for="item in roomList" :key="item.id" :data="item" class="room-item">
                <template #tags>
                  <div class="browse-time">
                    <van-icon name="clock-o" class="time-icon" />
                    <span class="time-text">{{ item.browseTime }}</span>
                  </div>
                </template>
              </RoomCard>
            </div>
          </template>
          <template v-else>
            <van-empty 
              image="search" 
              description="暂无浏览记录"
              class="empty-state"
            >
              <van-button 
                round 
                type="primary" 
                class="bottom-button"
                @click="goToSearch"
              >
                去看房
              </van-button>
            </van-empty>
          </template>
        </PullDownRefreshContainer>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { showConfirmDialog, showToast } from "vant";
import { getHistoryList, clearHistoryList } from "@/api/search";
import PullDownRefreshContainer from "@/components/PullDownRefreshContainer/PullDownRefreshContainer.vue";
import type { ReqPage } from "@/api/types";
import RoomCard from "@/components/RoomCard/RoomCard.vue";
import type { RoomInterface } from "@/api/search/types";

const router = useRouter();
const pullDownRefreshContainerRef =
  ref<InstanceType<typeof PullDownRefreshContainer>>();
console.log("RoomCard.props", RoomCard);
// 房间列表
// 定义个type
type RoomInterfaceWithBrowseTime = RoomInterface & { browseTime: string };
const roomList = ref<RoomInterfaceWithBrowseTime[]>([]);
// 分页获取房间的信息
async function getHistoryListHandler(pageInfo: ReqPage) {
  //   调用接口
  let { data } = await getHistoryList(pageInfo);
  console.log("pageInfo.current", pageInfo.current);
  let targetRecords = data.records.map(item => {
    return {
      // "id" | "roomNumber" | "rent" | "graphVoList" | "labelInfoList"
      id: item.roomId,
      roomNumber: item.roomNumber,
      rent: item.rent,
      graphVoList: item.roomGraphVoList,
      labelInfoList: [],
      apartmentInfo: {
        //   "name" | "provinceName" | "cityName" | "districtName"
        name: item.apartmentName || "",
        provinceName: item.provinceName || "",
        cityName: item.cityName || "",
        districtName: item.districtName || ""
      },
      //  浏览时间
      browseTime: item.browseTime
    };
  }) as unknown as RoomInterfaceWithBrowseTime[];
  if (pageInfo.current === 1) {
    roomList.value = targetRecords;
  } else {
    roomList.value = [...roomList.value, ...targetRecords];
  }
  pullDownRefreshContainerRef.value?.setFinished(
    roomList.value.length >= data.total
  );
}

// 返回上一页
const goBack = () => {
  router.back();
};

// 清除浏览历史
const clearHistory = async () => {
  try {
    await showConfirmDialog({
      title: '确认清除',
      message: '确定要清除所有浏览记录吗？',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    });
    
    // 调用清除历史的API
    await clearHistoryList();
    roomList.value = [];
    showToast('清除成功');
  } catch (error: any) {
    // 用户取消或API调用失败
    if (error?.message) {
      showToast(error.message || '清除失败，请重试');
    }
  }
};

// 跳转到搜索页面
const goToSearch = () => {
  router.push('/search');
};
</script>

<style scoped lang="less">
.browsing-history-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.header-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  :deep(.van-nav-bar__title) {
    color: white;
    font-weight: 600;
  }
  
  :deep(.van-nav-bar__text) {
    color: white;
  }
  
  :deep(.van-icon) {
    color: white;
  }
}

.page-content {
  padding-top: 46px; // NavBar高度
}

.stats-section {
  padding: 16px;
  margin-bottom: 8px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .stats-icon {
    font-size: 32px;
    color: #667eea;
    margin-right: 16px;
  }
  
  .stats-info {
    flex: 1;
    
    .stats-number {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }
    
    .stats-label {
      font-size: 14px;
      color: #666;
    }
  }
}

.content-container {
  padding: 0 16px 16px;
}

.room-list {
  .room-item {
    margin-bottom: 12px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
    
    &:hover {
      transform: translateY(-2px);
    }
  }
}

.browse-time {
  display: flex;
  align-items: center;
  background: rgba(102, 126, 234, 0.1);
  padding: 4px 8px;
  border-radius: 12px;
  
  .time-icon {
    font-size: 12px;
    color: #667eea;
    margin-right: 4px;
  }
  
  .time-text {
    font-size: 12px;
    color: #667eea;
  }
}

.empty-state {
  padding: 60px 20px;
  
  .bottom-button {
    margin-top: 16px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .stats-card {
    padding: 16px;
    
    .stats-icon {
      font-size: 28px;
      margin-right: 12px;
    }
    
    .stats-number {
      font-size: 20px;
    }
  }
  
  .content-container {
    padding: 0 12px 12px;
  }
}
</style>
